<template>
  <view class="department-content">
    <eui-page-frame :topHeight="100">
      <template #top>
        <eui-navbar title="选择部门" color="#303133" :backgroundColor="$uni-bg-color" rightIcon=" "></eui-navbar>
        <view class="top-view flex-row">
          <eui-search-bar
              ref="RdsSearchBar"
              v-model="searchCurrentValue"
              placeholder="请输入部门名称或编码"
              radius="10"
              bgColor="#F2F3F5"
              :foucs="true"
              :filterButton="true"
              @clear="clearSearch"
              @confirm="searchConfirm"
          >
          </eui-search-bar>
        </view>
      </template>
      <eui-page-content>
        <scroll-view
            scroll-y
            class="department-list"
        >
          <view class="department-item" v-for="(item, index) in departmentList" :key="index">
            <view class="item-content flex-row-between" @click.stop="selectDepartment(item)">
              <view class="name">{{item.c_name}}</view>
<!--              <view class="checked-box" >-->
<!--                <image src="@/static/img/icon_multiplebox_selected.png" class="checkedImage" v-if="item.checked"/>-->
<!--                <image src="@/static/img/icon_multiplebox_unselect.png" class="checkedImage" v-else/>-->
<!--              </view>-->
              <!-- <checkbox :checked="item.checked" :value="item.c_adno" color="#02B7E6" /> -->
              <radio :value="item.c_adno" :checked="item.checked" @click.stop="selectDepartment(item)"
                     :color="themeColor" :class="[theme]" style="transform:scale(0.8)" />
            </view>
          </view>
        </scroll-view>
      </eui-page-content>
      
      <template #bottom>
        <!-- <view class="bottom-bar flex-row-between">
          <view class="selected-info">

          </view>
          <eui-button type="base" title="确定" singleTag="online" @buttonClick="confirmSelect"/>
        </view> -->
      </template>
    </eui-page-frame>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { useThemeStore } from '@/store/themeStore'
import {useMainStore} from "@/store/modules/store"
import { getRdsUrl, rdsRequest } from "@/hooks/rdsServices"
import { useReceiptStore } from '@/store/useReceiptStore'
// 获取store实例
const receiptStore = useReceiptStore()

const themeStore = useThemeStore()
const { theme } = storeToRefs(themeStore)
const themeColor = ref(theme.value === 'theme-blue' ? '#02B7E6' : '#FF6430')

const mainStore = useMainStore()
const { loginInfo } = mainStore
const rdsUrl = getRdsUrl()

// 搜索关键词
const searchCurrentValue = ref('')

// 部门列表数据
const departmentList = ref([])

/**
 * 获取部门数据
 */
const getData = async () => {
    uni.showLoading({ title: "加载中...", mask: true })
    let params = {
      Id: loginInfo.sUser,
      c_name: searchCurrentValue.value
    }
    console.log("params",params);
    
    const result = await rdsRequest(rdsUrl.apiApi, '管易通60RMIS公共', 'GetUserStoreDepart', params)
    uni.hideLoading()
    
    // 获取store中已选择的部门数据
    const selectedDepartments = receiptStore.fromData.c_dname || []
    
    // 处理返回数据，根据store中的数据设置checked状态
    departmentList.value = result.ds2.map((item: any) => {
        const isSelected = selectedDepartments.some(
            (dept: any) => dept.c_adno === item.c_adno
        )
        return {
            ...item,
            checked: isSelected
        }
    })
    // 更新已选数量
    calculateSelected()
}

// 搜索确认修改
const searchConfirm = async (searchValue: {value: string}) => {
  if (!searchValue.value) {
    uni.showToast({
      title: '请输入搜索内容',
      icon: 'none'
    })
    return
  }
  // TODO: 搜索逻辑
  getData()
  
}

// 清除搜索修改
const clearSearch = async () => {
  searchCurrentValue.value = ''
 
}

// 最大可选数量
const maxSelect = ref(100)
// 已选数量
const selectedCount = ref(2)

// 选择部门
const selectDepartment = (item: any) => {
  // 先将所有项设为未选中
  departmentList.value.forEach((dept: any) => {
    dept.checked = false
  })
  // 设置当前项为选中
  item.checked = true;
  calculateSelected();
  confirmSelect();
}

// 计算已选数量
const calculateSelected = () => {
  selectedCount.value = departmentList.value.filter(item => item.checked).length
}

// 确认选择
const confirmSelect = () => {
  const selected = departmentList.value.filter(item => item.checked)
  console.log("selected", selected)
  
  // 将选中的部门保存到store中
  receiptStore.updateFromData('c_dname', selected)

  // 获取当前页面栈
  const pages = getCurrentPages()
  // 获取上一个页面的路由
  const prevPage = pages[pages.length - 2]
  if (prevPage) {
    const prevRoute = prevPage.route // 获取完整路由路径
    // 判断是否来自 list 或 detail 页面
    if (prevRoute === 'pages/BusiViews/StoreTransfer/list') {
      console.log('上一页是列表页')
      uni.navigateTo({
        url: '/pages/BusiViews/StoreTransfer/detail',
      })
    } else if (prevRoute === 'pages/BusiViews/StoreTransfer/detail') {
      console.log('上一页是详情页')
      uni.navigateBack()
    }
  }
}


// 在onLoad中初始化数据
onLoad(async () => {
  await getData()
})
</script>

<style lang="scss" scoped>
.department-content {
  ::v-deep .uni-checkbox-input{
    width: 32rpx!important;
    height: 32rpx!important;
  }

  ::v-deep .white-main {
    margin: 0;
    border-radius: 30rpx 30rpx 0 0;
  }

  .top-view {
    box-sizing: border-box;
    width: 100%;
    height: 88rpx;
    margin-bottom: 10rpx;

    ::v-deep .uni-searchbar-content {
      padding: 0 20rpx;
    }
    ::v-deep .uni-searchbar__box {
      width: 710rpx;
      height: 80rpx!important;
      border-radius: 20rpx;
      background: #FFFFFF!important;
    }

    ::v-deep .m-button {
      width: 104rpx;
      height: 60rpx;
      line-height: 60rpx;
      padding: 0!important;
      background: #409eff;
      border-radius: 16rpx;
    }

  }

  .department-list {
    width: 100%;
    height: 100%;
    padding: 0 20rpx;
    box-sizing: border-box;
    background: #FFFFFF;

    .department-item {
      padding: 20rpx 0;
      border-bottom: 1px solid #EEEEEE;
      .checkedImage{
        width: 32rpx;
        height: 32rpx;
      }
      .item-content {
        .name {
          font-size: 28rpx;
          color: #303133;
        }
      }
    }
  }

  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 122rpx;
    background: #FFFFFF;
    padding: 0 20rpx;
    box-sizing: border-box;
    box-shadow: 0rpx 0rpx 30rpx 0rpx rgba(0,0,0,0.08);

    .selected-info {
      height: 122rpx;
      font-size: 28rpx;
      //font-family: $uni-font-family;
      text-align: left;
      color: #222222;
      line-height: 122rpx;
    }

    ::v-deep .m-button {
      width: 232rpx;
      height: 82rpx;
      background: #409eff;
      border-radius: 16rpx;
      margin: 0;
    }
  }
}
</style> 